package cn.swust.service.serviceimpl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import cn.swust.model.ShopCarBean;
import cn.swust.service.ShopCarService;
import cn.swust.util.DBUtil;

public class ShopCarServicecImpl implements ShopCarService {

	public int addShopPro(ShopCarBean shop) {
		int ret = 0;
		try{
		String insertSql = "insert into shopcar(shopcar_allprice,shopcar_user) values " +
		"(" + shop.getAllPrice() + ",'" + shop.getUser() + "')";
		Connection conn = DBUtil.getConnection();
		Statement state = conn.createStatement();
		state.execute(insertSql, Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = state.getGeneratedKeys();
		while(rs.next())
			ret = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return ret;
	}

	public int delShopPro(int id) {
		String delSql = "delete from shopcar where shopcar_id = " + id;
		return DBUtil.updateSql(delSql);
	}

	public int modShopPro(int id, ShopCarBean shop) {
		String modSql = "update shopcar set shopcar_allprice = " + shop.getAllPrice() +
		",shopcar_user = '" + shop.getUser() +  "' where shopcar_id = " + id;
		return DBUtil.updateSql(modSql);
	}

	public ShopCarBean queryById(int id) {
		String insertSql = "select * from shopcar where shopcar_id = " + id;
		ResultSet rs = DBUtil.querySql(insertSql, DBUtil.creatStatement(DBUtil.getConnection()));
		ShopCarBean shop = new ShopCarBean();
		try {
			if (rs.next()) {
				shop.setId(rs.getInt("shopcar_id"));
				shop.setAllPrice(rs.getFloat("shopcar_allprice"));
				shop.setUser(rs.getString("shopcar_user"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return shop;
	}

	public ArrayList<ShopCarBean> queryByUser(String user) {
		String insertSql = "select * from shopcar where shopcar_user = '" + user + "'";
		ResultSet rs = DBUtil.querySql(insertSql, DBUtil.creatStatement(DBUtil.getConnection()));
		ArrayList<ShopCarBean> shopList = new ArrayList<ShopCarBean>();
		try {
			while (rs.next()) {
				ShopCarBean shop = new ShopCarBean();
				shop.setId(rs.getInt("shopcar_id"));
				shop.setAllPrice(rs.getFloat("shopcar_allprice"));
				shop.setUser(rs.getString("shopcar_user"));
				shopList.add(shop);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return shopList;
	}

}
